﻿using System;
using System.Html;
using enyo;

namespace JenkinsView
{
    public class JobModel : Model
    {
        public JenkinsJobData[] ListJobs()
        {
            return _svrData.Jobs;
        }

        private bool _refresh;
        internal void ReadJobsData(bool refresh)
        {
            if (DomainModel.Model.ServerManager.SelectedServerIndex < 0)
                return;
            _refresh = refresh;

            var svr = DomainModel.Model.ServerManager.ListCurrentServer();
            string url = svr.Url + DomainModel.API_SUFFIX;
            Console.Log("Call url: " + url);
            var ajax = new enyo.Ajax(new AjaxProperties()
            {
                Url = url
            });

            ajax.Go(new
            {
            });

            ajax.Response(this, this.GotServerData);
            ajax.Error(this, this.GotServerError);


            Console.Log("-->Notify wait.");
            DomainModel.Model.NotifyAll(DomainModel.ASYNC_CALL, DomainModel.WAIT);
        }

        private JenkinsServerData _svrData;
        private object GotServerData(Async call, object data)
        {
            //Console.Log(JSON.Stringify(data));

            _svrData = data as JenkinsServerData;

            DomainModel.Model.NotifyAll(DomainModel.ASYNC_CALL, DomainModel.DONE);
            if (!_refresh)
                DomainModel.Model.NotifyAll(DomainModel.PANEL_NAVIGATE, DomainModel.NEXT_VIEW);
            Notify(DomainModel.JOB_LIST_CHANGE, null);
            return null;
        }

        private object GotServerError(Async call, object data)
        {
            Console.Log("Ajax call error.");
            DomainModel.Model.NotifyAll(DomainModel.ASYNC_CALL, DomainModel.DONE);
            DomainModel.Model.NotifyAll(DomainModel.ERROR, null);
            return null;
        }

        private int _selectedJobIdx = -1;
        public int SelectedJobIndex
        {
            get { return _selectedJobIdx; }
            set { _selectedJobIdx = value; }
        }

        public JenkinsJobData ListCurrentJob()
        {
            return _svrData.Jobs[_selectedJobIdx];
        }
    }
}
